import InitShaders2 from '../lib/InitShaders2';
import MV from '../lib/MV';

import Triangle from './Triangle';

import vshader21 from '../shaders/vshader21.glsl';
import fshader21 from '../shaders/fshader21.glsl';

class Canvas {
    constructor(canvas) {
        this._canvas = canvas;

        this._canvas.width  = window.innerWidth - 20;
        this._canvas.height = window.innerHeight - 20;

        this._triangle = new Triangle();
    }

    render() {
        let points = this._triangle.getPoints();

        this._gl = WebGLUtils.setupWebGL(this._canvas);
        if (!this._gl) {
            alert("WebGL isn't available");
            return false;
        }

        //  Configure WebGL
        this._gl.viewport(0, 0, this._canvas.width, this._canvas.height);
        this._gl.clearColor(1.0, 1.0, 1.0, 1.0);
        
        //  Load shaders and initialize attribute buffers
        let program = InitShaders2.initShaders(this._gl, vshader21, fshader21);
        this._gl.useProgram(program);
        
        // Load the data into the GPU
        let bufferId = this._gl.createBuffer();
        this._gl.bindBuffer(this._gl.ARRAY_BUFFER, bufferId);
        this._gl.bufferData(this._gl.ARRAY_BUFFER, MV.flatten(points), this._gl.STATIC_DRAW);

        // Associate out shader letiables with our data buffer
        let vPos = this._gl.getAttribLocation(program, "vPosition");
        this._gl.vertexAttribPointer(vPos, 2, this._gl.FLOAT, false, 0, 0);
        this._gl.enableVertexAttribArray(vPos);


        this._gl.clear(this._gl.COLOR_BUFFER_BIT);
        this._gl.drawArrays(this._gl.TRIANGLES, 0, points.length);
    }

    twistTriangle(angle) {
        this._triangle.twist(angle);
        this.render();
    }

    divideTriangle(numberOfTimesToDivide) {
        this._triangle.setDivideNumber(numberOfTimesToDivide);
        this.render();
    }
}

module.exports = Canvas;
